﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using bmapi.HelperClass;
using bmapi.Models.DataEntity;
using static bmapi.Models.ShowModel;

namespace bmapi.Controllers
{
    [Route("staffmanage")]
    public class StaffManageController : PageController
    {
        [HttpGet]
        public HttpResponseMessage GetStaffs(int page = 1, int limit = 10)
        {
            int loginid = GetCrrentIDByToken();
            if (loginid == 0)
                return AssistFun.toJson(new { status = 201, tip = "不存在工号:0" });
            User user = GetUserByLoginID(loginid);
            int totalPage = 0;
            int totalRows = 0;
            DataTable dtList = new DataTable();
            if (user.power == 1)
                SQLCommand.GetDataListByPage("User_tb", "*", "last_time desc", " and PLID=" + user.PLID, limit, page, out totalPage, out totalRows, out dtList);
            else if (user.power == 2)
                SQLCommand.GetDataListByPage("User_tb", "*", "PLID asc,last_time desc", " and power=1", limit, page, out totalPage, out totalRows, out dtList);
            if (dtList != null)
            {
                List<User> users = AssistFun.DataTableToList<User>(dtList);
                //获取工序名称  
                List<ShowStaffInfo> pageshow = new List<ShowStaffInfo>();
                string PLName = "";
                for (int i = 0; i < users.Count; i++)
                {
                    List<CategoryInfo> categorynames = new List<CategoryInfo>();
                    if (users[i].code == 35 || users[i].code2 == 35 || users[i].code3 == 35)
                        categorynames = GetCategoryNameForPod(users[i].login_id);
                    if (user.power == 2)
                    {
                        PLName = GetPLNameBvPlid(users[i].PLID);
                        pageshow.Add(new ShowStaffInfo(users[i], MatchProNameByProCode(GetUserCodes(users[i])), categorynames, PLName));
                    }
                    else
                        pageshow.Add(new ShowStaffInfo(users[i], MatchProNameByProCode(GetUserCodes(users[i])), categorynames));
                }
                return AssistFun.toJson(new RespondModel(200, "成功", new data(totalRows, pageshow.ConvertAll(u => (object)u))));
            }
            else
            {
                return AssistFun.toJson(new RespondModel(201, "没有数据"));
            }
        }
        /// <summary>
        /// 获取员工的code 
        /// </summary> 
        /// <param name="users"></param>
        /// <returns></returns>
        private List<int> GetUserCodes(User user)
        {
            return new List<int>() { user.code, user.code2, user.code3 };
        }
        /// <summary>
        /// 修改员工信息  user实体做参数    
        /// </summary>  注意：若是该员工是检查特提示一定是code=35
        /// <param name="id"></param>
        [HttpPut]
        public HttpResponseMessage Put(dynamic obj)
        {
            string sql = "update User_tb set code=@code,code2=@code2,code3=@code3,password=@pwd,mach_id=@mid,state=@state,grouping=@grouping where login_id=@loginid";
            List<SQLCommand> cmds = new List<SQLCommand>();
            SQLCommand sc = new SQLCommand(sql);
            int code = Convert.ToInt32(obj.code);
            int loginid = Convert.ToInt32(obj.login_id);
            sc.Add("@code", code);
            sc.Add("@code2", Convert.ToInt32(obj.code2.ToString()));
            sc.Add("@code3", Convert.ToInt32(obj.code3.ToString()));
            sc.Add("@pwd", obj.password.ToString());
            sc.Add("@mid", Convert.ToInt32(obj.mach_id));
            sc.Add("@state", Convert.ToInt32(obj.state));
            sc.Add("@grouping", Convert.ToInt32(obj.grouping));
            sc.Add("@loginid", loginid);
            cmds.Add(sc);
            if (code == 35 || Convert.ToInt32(obj.code2) == 35 || Convert.ToInt32(obj.code3) == 35)
            {
                //事务 
                if (obj.categories != null)
                {
                    List<CategoryInfo> categories = obj.categories.ToObject<List<CategoryInfo>>();
                    if (categories.Count > 0)
                    {
                        if (!GetPod(categories, ref cmds, loginid, false))
                            return AssistFun.toJson(new RespondModel(201, "修改失败"));
                    }
                    else
                        DeleCategoryForUSer(loginid);  //取消所有品类选择 
                }
            }
            if (SQLCommand.ExecTran(cmds) == 0)
                return AssistFun.toJson(new RespondModel(201, "修改失败"));
            else
                return AssistFun.toJson(new RespondModel(200, "成功"));
        }
        /// <summary>
        /// 新增员工  只有两个信息 工号login_id  工序 code 默认密码888888
        /// </summary>    
        /// <param name="obj"></param>
        [HttpPost]
        public HttpResponseMessage Post(dynamic obj)
        {
            if (obj == null)
                return AssistFun.toJson(new { status = 201, tip = "请提供新增员工的信息" });
            try
            {               
                int currentLid = GetCrrentIDByToken();
                if (currentLid == 0)
                    return AssistFun.toJson(new { status = 201, tip = "不存在工号:0" });
                User user = GetUserByLoginID(currentLid);
                int loginid = Convert.ToInt32(obj.login_id);
                if(loginid<=0)
                    return AssistFun.toJson(new { status = 201, tip = "请输入有效工号" });
                int code = Convert.ToInt32(obj.code);
                SQLCommand sc = null;
                sc = new SQLCommand("select login_id,power,PLID from User_tb where login_id=" + loginid);
                DataRow dr = sc.ExecuteOneRow();
                //如果新增的员工工号已存在，则将该员工的流水线改为当前登录主管所在的流水线  如果已经是本流水线员工  提示  已存在该员工
                if (dr != null)
                {
                    if (Convert.ToInt32(dr["power"]) == 2)
                        return AssistFun.toJson(new RespondModel(201, "你无权操作管理员"));
                    if(Convert.ToInt32(dr["PLID"])==user.PLID)
                        return AssistFun.toJson(new RespondModel(201, " 已存在该员工"));
                    sc = new SQLCommand("update user_tb set PLID=@PLID,state=0 where login_id=@login_id");
                    sc.Add("@PLID", user.PLID);
                    sc.Add("@login_id", loginid);
                    if (sc.ExecuteNonQuery() == 1)
                        return AssistFun.toJson(new RespondModel(200, "该用户已转岗至本流水线"));
                    else
                        return AssistFun.toJson(new RespondModel(201, "转岗失败"));
                }
                else
                {
                    List<SQLCommand> cmds = new List<SQLCommand>();
                    sc = new SQLCommand("insert into User_tb(login_id,code,code2,code3,PLID,power,grouping) values(@loginid,@code,@code2,@code3,@plid,@power,@grouping)");
                    sc.Add("@loginid", loginid);
                    sc.Add("@code", code);
                    sc.Add("@code2", Convert.ToInt32(obj.code2));
                    sc.Add("@code3", Convert.ToInt32(obj.code3));
                    sc.Add("@plid", user.PLID);
                    if (user.power == 2)
                        sc.Add("@power", 1);
                    else
                        sc.Add("@power", 0);
                    sc.Add("@grouping", Convert.ToInt32(obj.grouping));
                    cmds.Add(sc);
                    if (code == 35 || Convert.ToInt32(obj.code2) == 35 || Convert.ToInt32(obj.code3) == 35)
                    {
                        List<CategoryInfo> categories = obj.categories.ToObject<List<CategoryInfo>>();
                        if (categories.Count > 0)
                            GetPod(categories, ref cmds, loginid);

                    }
                    if (SQLCommand.ExecTran(cmds) != 0)
                        return AssistFun.toJson(new RespondModel(200, "成功"));
                    else
                        return AssistFun.toJson(new RespondModel(201, "新增失败"));
                    //if (sc.ExecuteNonQuery() == 1)
                    //    return AssistFun.toJson(new RespondModel(200, "成功"));
                    //else
                    //    return AssistFun.toJson(new RespondModel(201, "新增失败"));
                }
            }
            catch (Exception e)
            {
                return AssistFun.toJson(new RespondModel(201, e.Message));
            }
            
        }

        private bool GetPod(List<CategoryInfo> categories, ref List<SQLCommand> cmds, int loginid, bool isNew = true)
        {
            if (!isNew)
            {
                if (DeleCategoryForUSer(loginid))
                    InsertCategoryUSer(categories, ref cmds, loginid);
                else
                    return false;
            }
            else
                InsertCategoryUSer(categories, ref cmds, loginid);
            return true;
        }
        /// <summary>
        /// 在修改品类时先删除当前用户之前所有的品类
        /// </summary>  
        /// <param name="categories"></param>
        /// <param name="loginid"></param>
        /// <returns></returns>
        private bool DeleCategoryForUSer(int loginid)
        {
            string sql = "select login_id from CategoryUser_tb where login_id=@loginid";
            SQLCommand sc = new SQLCommand(sql, "@loginid", loginid);
            if (sc.ExecuteScalar() == null)
                return true;
            else
            {
                string cateuser = "delete from CategoryUser_tb where login_id=@loginid";
                sc = new SQLCommand(cateuser,"@loginid", loginid);
                if (sc.ExecuteNonQuery() < 0)
                    return false;
                else
                    return true;
            }

        }

        private void InsertCategoryUSer(List<CategoryInfo> categories, ref List<SQLCommand> cmds, int loginid)
        {
            foreach (CategoryInfo item in categories)
            {
                string cateuser = "insert into CategoryUser_tb(category_id,category_name,login_id) values(@categoryId,@cName,@loginid)";
                SQLCommand cusc = new SQLCommand(cateuser);
                cusc.Add("@categoryId", item.Id);
                cusc.Add("@cName", item.CategoryName);
                cusc.Add("@loginid", loginid);
                cmds.Add(cusc);
            }
        }

        /// <summary>
        /// 删除员工 
        /// </summary>    
        /// <param name="obj">工号</param>
        /// <returns></returns>
        [HttpDelete]
        public HttpResponseMessage Delete(dynamic obj)
        {            
            if (obj == null)
                return AssistFun.toJson(new { status = 201, tip = "请提供工号" });
            else
            {
                List<CategoryInfo> categories = obj.CategoryName.ToObject<List<CategoryInfo>>();
                List<SQLCommand> cmds = new List<SQLCommand>();
                string sql = "delete from CategoryUser_tb where login_id=@loginid";
                int loginid = Convert.ToInt32(obj.login_id);
                if (categories!=null && categories.Count > 0)
                    cmds.Add(new SQLCommand(sql,"@loginid",loginid));
                sql = "delete User_tb where login_id=@loginid";
                cmds.Add(new SQLCommand(sql, "@loginid", loginid));
                if(SQLCommand.ExecTran(cmds)==0)
                    return AssistFun.toJson(new { status = 201, tip = "失败" });
                return AssistFun.toJson(new { status = 200, tip = "成功" });
            }
        }
    }
}
